package com.gouaixin.bee.beeframework2.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.util.AbDialogUtil;
import com.ab.util.AbImageUtil;
import com.ab.util.AbToastUtil;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.component.RoundImageView;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by Administrator on 2015/3/10.
 */
//完善资料界面
public class B12_wanshanZiliaoActivity extends FragmentActivity {
    Context context=B12_wanshanZiliaoActivity.this;

    RoundImageView icon;
    TextView zhiyeTv,xueliTv,shouruTv,hightTv,hunyinTv,queding;
    LinearLayout zhiyeBt,xueliBt,shouruBt,hightBt,hunyinBt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b12_wanshanziliao);

        initIntent();
        
        initHead();
        initContent();

        setListener();

    }


    private void setListener() {

        zhiyeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("修改用户信息");
                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_ziliaoedit, null);
                AbDialogUtil.showDialog(mView);

                TextView title= (TextView) mView.findViewById(R.id.title);
                final EditText edit= (EditText) mView.findViewById(R.id.edit);
                TextView quxiao= (TextView) mView.findViewById(R.id.quxiao);
                TextView kaitong= (TextView) mView.findViewById(R.id.kaitong);

                title.setText("职业");
//                edit.setText(myuser.getZhiye());

                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(context);
                    }
                });
                kaitong.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLog.e("修改用户信息：开始实现");
                        String str=edit.getText().toString();
                        if(str.equals("")){
                            AbToastUtil.showToast(context,"输入内容不能为空");
                            return;
                        }
                        USER myuser = BmobUser.getCurrentUser(context, USER.class);
                        myuser.setZhiye(str);
                        myuser.update(context, new UpdateListener() {
                            @Override
                            public void onSuccess() {
//                                AbToastUtil.showToast(context, "更新用户信息成功");
                                AbDialogUtil.removeDialog(context);
                                initData();
                            }

                            @Override
                            public void onFailure(int i, String s) {
//                                AbToastUtil.showToast(context, "更新用户信息失败："+s);
                                AbDialogUtil.removeDialog(context);

                            }
                        });
                    }
                });
            }
        });

        xueliBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("修改用户信息");
                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_ziliaoedit, null);
                AbDialogUtil.showDialog(mView);

                TextView title= (TextView) mView.findViewById(R.id.title);
                final EditText edit= (EditText) mView.findViewById(R.id.edit);
                TextView quxiao= (TextView) mView.findViewById(R.id.quxiao);
                TextView kaitong= (TextView) mView.findViewById(R.id.kaitong);

                title.setText("学历");
//                edit.setText(myuser.getXueli());

                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(context);
                    }
                });
                kaitong.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLog.e("修改用户信息：开始实现");
                        String str=edit.getText().toString();
                        if(str.equals("")){
                            AbToastUtil.showToast(context,"输入内容不能为空");
                            return;
                        }
                        USER myuser = BmobUser.getCurrentUser(context, USER.class);
                        myuser.setXueli(str);
                        myuser.update(context, new UpdateListener() {
                            @Override
                            public void onSuccess() {
//                                AbToastUtil.showToast(context, "更新用户信息成功");
                                AbDialogUtil.removeDialog(context);
                                initData();
                            }

                            @Override
                            public void onFailure(int i, String s) {
//                                AbToastUtil.showToast(context, "更新用户信息失败："+s);
                                AbDialogUtil.removeDialog(context);

                            }
                        });

                    }
                });

            }
        });

        shouruBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("修改用户信息");
                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_ziliaoedit, null);
                AbDialogUtil.showDialog(mView);

                TextView title= (TextView) mView.findViewById(R.id.title);
                final EditText edit= (EditText) mView.findViewById(R.id.edit);
                TextView quxiao= (TextView) mView.findViewById(R.id.quxiao);
                TextView kaitong= (TextView) mView.findViewById(R.id.kaitong);

                title.setText("收入");
//                edit.setText(myuser.getShouru());

                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(context);
                    }
                });
                kaitong.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLog.e("修改用户信息：开始实现");
                        String str=edit.getText().toString();
                        if(str.equals("")){
                            AbToastUtil.showToast(context,"输入内容不能为空");
                            return;
                        }
                        USER myuser = BmobUser.getCurrentUser(context, USER.class);
                        myuser.setShouru(str);
                        myuser.update(context, new UpdateListener() {
                            @Override
                            public void onSuccess() {
//                                AbToastUtil.showToast(context, "更新用户信息成功");
                                AbDialogUtil.removeDialog(context);
                                initData();
                            }

                            @Override
                            public void onFailure(int i, String s) {
//                                AbToastUtil.showToast(context, "更新用户信息失败："+s);
                                AbDialogUtil.removeDialog(context);

                            }
                        });



                    }
                });

            }
        });
        hightBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("修改用户信息");
                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_ziliaoedit, null);
                AbDialogUtil.showDialog(mView);

                TextView title= (TextView) mView.findViewById(R.id.title);
                final EditText edit= (EditText) mView.findViewById(R.id.edit);
                TextView quxiao= (TextView) mView.findViewById(R.id.quxiao);
                TextView kaitong= (TextView) mView.findViewById(R.id.kaitong);

                title.setText("身高");
//                edit.setText(myuser.getHeight());

                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(context);
                    }
                });
                kaitong.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLog.e("修改用户信息：开始实现");
                        String str=edit.getText().toString();
                        if(str.equals("")){
                            AbToastUtil.showToast(context,"输入内容不能为空");
                            return;
                        }
                        USER myuser = BmobUser.getCurrentUser(context, USER.class);
                        myuser.setHeight(str);
                        myuser.update(context, new UpdateListener() {
                            @Override
                            public void onSuccess() {
//                                AbToastUtil.showToast(context, "更新用户信息成功");
                                AbDialogUtil.removeDialog(context);
                                initData();
                            }

                            @Override
                            public void onFailure(int i, String s) {
//                                AbToastUtil.showToast(context, "更新用户信息失败："+s);
                                AbDialogUtil.removeDialog(context);

                            }
                        });



                    }
                });

            }
        });

        hunyinBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("修改用户信息");
                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_ziliaoedit, null);
                AbDialogUtil.showDialog(mView);

                TextView title= (TextView) mView.findViewById(R.id.title);
                final EditText edit= (EditText) mView.findViewById(R.id.edit);
                TextView quxiao= (TextView) mView.findViewById(R.id.quxiao);
                TextView kaitong= (TextView) mView.findViewById(R.id.kaitong);

                title.setText("婚姻");
//                edit.setText(myuser.getZhiye());

                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(context);
                    }
                });
                kaitong.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLog.e("修改用户信息：开始实现");
                        String str=edit.getText().toString();
                        if(str.equals("")){
                            AbToastUtil.showToast(context,"输入内容不能为空");
                            return;
                        }
                        USER myuser = BmobUser.getCurrentUser(context, USER.class);
                        myuser.setHunyin(str);
                        myuser.update(context, new UpdateListener() {
                            @Override
                            public void onSuccess() {
//                                AbToastUtil.showToast(context, "更新用户信息成功");
                                AbDialogUtil.removeDialog(context);
                                initData();
                            }

                            @Override
                            public void onFailure(int i, String s) {
//                                AbToastUtil.showToast(context, "更新用户信息失败："+s);
                                AbDialogUtil.removeDialog(context);

                            }
                        });



                    }
                });

            }
        });


    }

    private void initIntent() {
        Intent it=getIntent();

        isMain=it.getBooleanExtra("isMain",false);
    }

    /***
     * 内容区域的监听
     */
    private void initContent() {
        icon= (RoundImageView) findViewById(R.id.user_icon);
        zhiyeTv= (TextView) findViewById(R.id.zhiyeTv);
        xueliTv= (TextView) findViewById(R.id.xueliTv);
        shouruTv= (TextView) findViewById(R.id.shouruTv);
        hightTv= (TextView) findViewById(R.id.hightTv);
        hunyinTv= (TextView) findViewById(R.id.hunyinTv);
        queding= (TextView) findViewById(R.id.queding);
        zhiyeBt= (LinearLayout) findViewById(R.id.zhiyeBt);
        xueliBt= (LinearLayout) findViewById(R.id.xueliBt);
        shouruBt= (LinearLayout) findViewById(R.id.shouruBt);
        hightBt= (LinearLayout) findViewById(R.id.hightBt);
        hunyinBt= (LinearLayout) findViewById(R.id.hunyinBt);

        initData();

        icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_xuanzetupian, null);
                AbDialogUtil.showDialog(mView);
//
                TextView lijiPaizhao = (TextView) mView.findViewById(R.id.lijipaizhao);
                TextView bendiXiangce = (TextView) mView.findViewById(R.id.bendixiangce);
                lijiPaizhao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        //下面这句指定调用相机拍照后的照片存储的路径
                        file_path=new Date().getTime()+".png";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                .fromFile(new File(Environment
                                        .getExternalStorageDirectory(),
                                        file_path)));
                        startActivityForResult(intent, 1);
                        AbDialogUtil.removeDialog(context);
                    }
                });
                bendiXiangce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent2 = new Intent();
                        intent2.setType("image/*");
                        intent2.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intent2, 2);
                        AbDialogUtil.removeDialog(context);
                    }
                });
            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                USER myuser = BmobUser.getCurrentUser(context, USER.class);

                myuser.update(context, new UpdateListener() {
                    @Override
                    public void onSuccess() {
                        AbToastUtil.showToast(context, "更新用户信息成功");
                        tiaozhuan();

                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
            }
        });

    }

    /***
     * 初始化个人信息
     */
    USER myuser;
    private void initData() {
        mLog.e("初始化个人信息：");
        BmobQuery<USER> query = new BmobQuery<USER>();
        query.getObject(context, BmobUser.getCurrentUser(context).getObjectId(), new GetListener<USER>() {
            @Override
            public void onSuccess(USER user) {
                USER myuser = user;
                BmobFile micon = myuser.getIcon();






                if (micon != null) {
                    String url = micon.getFileUrl(context);
                    ImageLoader.getInstance().displayImage(url, icon);
                } else {
                    icon.setImageResource(R.drawable.init_reg_upload);
                }
                myuser= BmobUser.getCurrentUser(context, USER.class);
                if(myuser.getZhiye()!=null){
                    zhiyeTv.setText(myuser.getZhiye());
                }
                if(myuser.getXueli()!=null){
                    xueliTv.setText(myuser.getXueli());
                }
                if(myuser.getShouru()!=null){
                    shouruTv.setText(myuser.getShouru());
                }
                if(myuser.getHeight()!=null){
                    hightTv.setText(myuser.getHeight());
                }
                if(myuser.getHunyin()!=null){
                    hunyinTv.setText(myuser.getHunyin());
                }
                if(myuser.getIcon()!=null){

                    String url=myuser.getIcon().getFileUrl(context);
                    mLog.e("头像的网址：" + url);
                    ImageLoader.getInstance().displayImage(url, icon);
                }else {
                    mLog.e("头像为空：");
                }

//
//                mLog.e("jid:" + myuser.getName());
//                mLog.e("jid:" + myuser.getUsername());
//                jid.setText(myuser.getName());
//                jid.setText("jid:" + myuser.getUsername());
//                if (myuser.getYbi() != null ) {
//                    String ybi=myuser.getYbi();
//                    yBi.setText(ybi);
//                }else{
//                    yBi.setText("0");
//                }
//
//
//                if (myuser.getAibi() != null ) {
//                    String aibi=myuser.getAibi();
//                    aiBi.setText(aibi);
//                }else{
//                    aiBi.setText("0");
//                }

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });


    }

    /***
     * 头部的监听
     */
    private void initHead() {
        //顶部
        ImageView back;//返回
        TextView title;//标题

        back= (ImageView) findViewById(R.id.back);
        title= (TextView) findViewById(R.id.title);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tiaozhuan();
            }
        });
    }


    String file_path;//拍照图片路径
    String file_path2;//裁剪后的图片路径

    @Override

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 如果是直接从相册获取
            case 2:
                if (data != null && data.getData() != null) {

                    mLog.e("直接从相册获取:返回非空");
                    startPhotoZoom(data.getData());


                } else {
                    mLog.e("直接从相册获取:返回为空");
                }

                break;
            // 如果是调用相机拍照时
            case 1:
                if (data != null && data.getData() != null) {
                    mLog.e("调用相机拍照时:返回非空");
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/" + file_path);
                    if (Uri.fromFile(temp) != null) {
                        startPhotoZoom(Uri.fromFile(temp));
                    }
                } else {
                    mLog.e("调用相机拍照时:返回为空");
                }




                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */
                if(data != null){
                    setPicToView(data);
                }
                break;
            default:
                break;

        }




    }

    private void uploadBitmap(final Bitmap bitmap) {


        mLog.e("进入上传图片的方法：");

        file_path2=new Date().getTime()+".png";

        if (saveBitmap2file(bitmap, file_path2)) {
            mLog.e("图片转文件成功：" + file_path2);

            final BmobFile file = new BmobFile(new File("/sdcard/" + file_path2));

            mLog.e("文件转bomb成功：url");



            file.upload(context, new UploadFileListener() {
                @Override
                public void onProgress(Integer integer) {
                    mLog.e("文件上传成功进度：" + integer);
                }

                @Override
                public void onSuccess() {
                    mLog.e("文件上传成功：" + file_path2);
                    icon.setImageBitmap(AbImageUtil.toRoundBitmap(bitmap));
                    PreferencesUtils.putString(context, "icon", file.getFileUrl(context));

                    USER myuser = BmobUser.getCurrentUser(context, USER.class);
                    myuser.setIcon(file);
                    myuser.update(context, new UpdateListener() {
                        @Override
                        public void onSuccess() {
//                            AbToastUtil.showToast(context, "更新用户头像成功");
                            PreferencesUtils.putString(context, "icon", file.getFileUrl(context));

                        }

                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });

                }

                @Override
                public void onFailure(int i, String s) {
                    AbToastUtil.showToast(context,"网络故障，请稍后再试");
                    mLog.e("文件上传失败：" + s);

                }
            });


        } else {
            mLog.e("图片转文件失败：");
        }


    }


    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri,
                proj,                 // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);                 // Order-by clause (ascending by jid)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    boolean saveBitmap2file(Bitmap bmp, String filename) {
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream("/sdcard/" + filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return bmp.compress(format, quality, stream);
    }


    /**
     * 裁剪图片方法实现
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            mLog.e("显示裁剪后的图片：");


            uploadBitmap(photo);

        }
    }




    /**
     * 监听返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        long currentTime = System.currentTimeMillis();

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            tiaozhuan();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /***
     * 跳转界面的方法
     */
    boolean isMain=false;//是否是从主界面跳转过来的
    private void tiaozhuan() {
        if(isMain==true){
            finish();
        }else {
            Intent it = new Intent().setClass(context, MyMainActivity.class);
            startActivity(it);
            finish();
        }
    }
}
